package heman.server.processor;



import heman.server.controllerchain.DefaultServerChain;
import ks.framework.common.Message;
import ks.framework.communicator.Communicator;
import ks.framework.debug.Debug;

import ks.server.controllers.ServerControllerChain;

/**
 * Server-side processor of messages received from client.
 * <p>
 * This class supports the registration (and unregistration) of controllers
 * to handle specific messages. Use this wisely.
 * <p>
 * Note that all registration is handled statically. For each message to be
 * processed, a new Processor object handles it cleanly.
 * 
 * @author George Heineman
 */
public class ServerProcessor  {
	
	/** Agent who knows how to communicate back to client(s). */
	Communicator com;
		
	/**
	 * The ServerProcessor knows how to respond to a message.
	 */
	public ServerProcessor (Communicator com) {
		this.com = com;
	}
	
	/** 
	 * Head of the chain of processors. Defaults to one built in. 
	 */
	protected static ServerControllerChain head = new DefaultServerChain();
	
	/** Return the head of the chain of agents managing the server-side controllers. */
	public static ServerControllerChain head() {
		return head;
	}
	
	/** NOTE: Only to be called by testing code. */
	public static void resetControllers() {
		head = new DefaultServerChain();
	}
	
	/**
	 * Process the given message and return <code>true</code> if the 
	 * message has been handled. Note that the return code says nothing
	 * about the success of the controller processing the message, only that
	 * it was handled
	 * 
	 * @param m  the message received from a client to process. Note that
	 *           {@link Message#getOriginator()} method can be used to determine
	 *           the client on whose behalf the message is being processed.
	 * 
	 * @return  <code>false</code> if no controller has been registered
	 * to handle the given message
	 */
	public boolean process( Message m) {

		Debug.println("Received:" + m.toString());
		
		// delegate the processing on to the chain of agents that know of 
		// all controllers on the server side.
		return head.process(com, m);
	}

}
